import re

input_file = 'srt_txt/文案.txt'
output_file = 'srt_txt/txt.txt'

# 用于匹配标点符号的正则表达式
punctuation_pattern = r'[。，,！?？：；、“”‘’.-]'
# 用于匹配行首数字的正则表达式
number_pattern = r'^\d+'

with open(input_file, 'r', encoding='utf-8') as f:
    lines = [line.rstrip() for line in f.readlines()]

with open(output_file, 'w', encoding='utf-8') as f:
    prev_line_empty = True
    for line in lines:
        # 删除所有标点符号
        line = re.sub(punctuation_pattern, ' ', line)
        # 将行首数字替换为 [image数字]
        line = re.sub(number_pattern, lambda m: f'[image{m.group(0)}]', line)

        # 检查当前行是否为空
        current_line_empty = line.strip() == ''

        # 如果当前行不为空，或者上一行不为空，则写入修改后的行
        if not current_line_empty or not prev_line_empty:
            f.write(line)

        # 更新prev_line_empty的值
        prev_line_empty = current_line_empty

#重新排列
with open(output_file, 'r', encoding='utf-8') as f:
    content = f.read()

content = content.replace('[image', '\n[image')
content = content.replace(" ", "")

with open(output_file, 'w', encoding='utf-8') as f:
    f.write(content)

#删除第一行 空白行
with open(output_file, 'r', encoding='utf-8') as f:
    content = f.readlines()

content = [line for line in content if line.strip()]

with open(output_file, 'w', encoding='utf-8') as f:
    f.write("".join(content))


def count_lines(file_path):
    with open(file_path, 'r', encoding='utf-8') as f:
        return sum(1 for line in f)

print('文案行数:', count_lines(output_file))
